source("recodes.R")
source("subgroup function.R")

library(reshape2)
library(ggplot2)
library(stargazer)
library(arm)
library(magrittr)

# Figure B

anger.model <- lm(anger.av ~ anger + anxiety, wave2)
anxiety.model <- lm(anxiety.av ~ anger + anxiety, wave2)
anganx.model <- lm(I(anger.av - anxiety.av) ~ anger + anxiety, wave2)

coefs <- c(coef(anger.model)[2], coef(anger.model)[3], 
           coef(anxiety.model)[2], coef(anxiety.model)[3],
           coef(anganx.model)[2], coef(anganx.model)[3])

ses <- c(se.coef(anger.model)[2], se.coef(anger.model)[3], 
           se.coef(anxiety.model)[2], se.coef(anxiety.model)[3],
           se.coef(anganx.model)[2], se.coef(anganx.model)[3])

df <- data.frame(coefs = coefs, ses = ses, variable = rep(c("Anger", "Anxiety")), outcome = rep(c("Self-Reported Anger", "Self-Reported Anxiety", "Self-Reported Anger - Anxiety"), each = 2))

limits <- aes(ymax = coefs + ses*1.96, ymin = coefs - ses*1.96)

df$outcome <- factor(df$outcome, levels = levels(df$outcome)[c(1,3,2)], labels = c("Self-Reported Anger", "Self-Reported Anxiety", "Self-Reported Anger - Anxiety"))

df %>% ggplot(aes(x = outcome, y = coefs, group = variable, col = variable)) + geom_pointrange(limits, position=position_dodge(width=.5)) + labs(col = "Manipulation", y = "Average Treatment Effect", title = "Manipulation Checks") + xlab("Outcomes") + geom_hline(yintercept = 0) + ylim(c(-2,2)) + theme_bw() + theme(plot.title = element_text(hjust = 0.5)) 

# Figure C

x <- data.frame(Asian=wave2$local_asian,Black=wave2$local_black,Hispanic=wave2$local_hispanic,White=wave2$local_white)
data<- melt(x)

ggplot(data,aes(x=value, fill=variable)) + geom_density(alpha=.75, bw=5) + labs(x = "Subjective Percentages", y = "Density", title = "Local Perceptions", fill = "Demographics") + scale_fill_grey(start = 0, end = 1) + theme_bw() + theme(plot.title = element_text(hjust = 0.5))

x <- data.frame(Asian=wave2$national_asian,Black=wave2$national_black,Hispanic=wave2$national_hispanic,White=wave2$national_white)
data<- melt(x)

ggplot(data,aes(x=value, fill=variable)) + geom_density(alpha=.75, bw=5) + labs(x = "Subjective Percentages", y = "Density", title = "National Perceptions", fill = "Demographics") + scale_fill_grey(start = 0, end = 1) + theme_bw() + theme(plot.title = element_text(hjust = 0.5))

# Table D

wave2$over100_local <- as.numeric(rowSums(wave2[,c("local_black","local_white","local_asian","local_hispanic")]) > 100)
wave2$over100_national <- as.numeric(rowSums(wave2[,c("national_black","national_white","national_asian","national_hispanic")]) > 100)

stargazer(lm(over100_local ~ anger + anxiety, wave2), lm(over100_national ~ anger + anxiety, wave2))

# Figure E

subgroup_analysis("white", binary = TRUE)
subgroup_analysis("income")
subgroup_analysis("education")
subgroup_analysis("auth")
subgroup_analysis("ideology")


